package com.qf.controller;

import com.qf.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取请求参数（标识符，方法名）
        String methodStr = req.getParameter(Constants.TAG);

        //2、如果method没有获取到值  我们就跳转到首页
        if (methodStr  ==  null || "".equals(methodStr)){
            methodStr = Constants.INDEX;
        }

        //3、反射调用对应的业务逻辑方法
        //获取class 类
        Class clazz = this.getClass();

//        String name = clazz.getName();

        try {
            //4、从类中获取方法对象
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);

            //5、执行从类中获取的方法对象，接收方法执行结果
            Object reslut = method.invoke(this, req, resp);

            if (reslut != null){
                String jump = (String)reslut;

                if (jump.startsWith(Constants.FORWARD)){
//                  获取路径
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
//                 执行请求转发
                    req.getRequestDispatcher(path).forward(req,resp);
                }else if (jump.startsWith(Constants.REDIRECT)){
                    //获取路径
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    //执行重定向
                    resp.sendRedirect(path);
                }else {
                    resp.getWriter().println(jump);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
